import 'package:automated_test/common/myLog.dart';
import 'package:sqflite/sqflite.dart';

class DbHelper {
  static const String _dbName = "device.db";
  static const String TABLE_GATE = "gate";
  static const String COLUMN_MAC = "mac";
  static const String _CREATE_TAB_GATE =
      'CREATE TABLE IF NOT EXISTS $TABLE_GATE($COLUMN_MAC TEXT);';

  static late final Database _db;

  static Future init() async {
    MyLog.w("init", "init");
    _db = await openDatabase(
      await getDatabasesPath() + "/" + _dbName,
      version: 1,
      onCreate: _createDb,
    );
  }

  static Future _createDb(Database db, int version) async {
    MyLog.w("_createDb", "$version");
    var batch = db.batch();
    batch.execute(_CREATE_TAB_GATE);
    await batch.commit();
  }

  static void insertGate(String mac) async {
    await _db.insert(TABLE_GATE, {"mac": mac});
  }

  ///是否存在[mac]
  static Future<bool> existsGate(String mac) async {
    List<Map<String, Object?>> list = await _db.query(TABLE_GATE,
        columns: [COLUMN_MAC], where: "$COLUMN_MAC = ? ", whereArgs: [mac]);
    MyLog.i("queryGate", "$list");
    if (list.isEmpty) {
      return false;
    }
    return true;
  }

  ///查询所有的闸机mac
  static Future<List<String>?> queryGates() async {
    List<Map<String, Object?>> maps =
        await _db.rawQuery("SELECT * FROM $TABLE_GATE");
    if (maps.isEmpty) return null;
    List<String> result = [];
    maps.forEach((element) {
      result.add(element["mac"].toString());
    });
    return result;
  }

  ///模糊查询 mac
  static Future<List<String>?> fuzzyQueryGate(String query) async {
    List<Map<String, Object?>> maps = await _db.query(
      TABLE_GATE,
      columns: [COLUMN_MAC],
      where: "$COLUMN_MAC like ?",
      whereArgs: ["%$query%"],
    );

    if (maps.isEmpty) return null;
    List<String> result = [];
    maps.forEach((element) {
      result.add(element["mac"].toString());
    });
    return result;
  }

  static Future deleteGate(String mac) async {
    int count = await _db
        .delete(TABLE_GATE, where: "$COLUMN_MAC = ?", whereArgs: [mac]);

    if (count > 0) {
      return true;
    }
    return false;
  }
}
